<template>
  <div>
    <h1 class="chattitle">和{{ toUserName }}聊天中</h1>
    <div class="reply-box margin_top100">
      <ul>
        <li v-if="!finished" class="text-center">
          <a @click="getMessages" class="colorblue font26">查看更多消息</a>
        </li>
        <li v-for="(item, index) in messages" :key="index">
          <p class="text-center">
            <span>{{ formatTime(item.send_time) }}</span>
          </p>
          <div v-if="item.from_user_id == userdataid">
            <div class="my">
              <user-avatar :src="avatar" className="useravatar"></user-avatar>
              <div class="detail">
                <!-- <div class="message">{{ item.content }}</div> -->
                <div v-if="isImage(item.content)" class="msg-img" v-html="$Shared.buildImageContent(item.content)" @click="showImage(item.content)"></div>
                <div v-else class="message" v-html="item.content"></div>
              </div>
            </div>
          </div>
          <div v-else>
            <div class="user">
              <user-avatar :src="toUserHeadImage" className="useravatar"></user-avatar>
              <div class="detail">
                <!-- <div class="message">{{ item.content }}</div> -->
                <div v-if="isImage(item.content)" class="msg-img" v-html="$Shared.buildImageContent(item.content)" @click="showImage(item.content)"></div>
                <div v-else class="message" v-html="item.content"></div>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <a name="end" ></a>
    <div class="mesbox">
      <el-input placeholder="请输入内容" v-model="message" @keydown.enter.native="sendMessage" class="input-with-select">    
        <el-button slot="append" @click="sendMessage">发送</el-button>
      </el-input>
      <!-- <el-input v-model="message" clearable placeholder="请输入消息" type="textarea" rows="1" :autosize="messageSize">
        <el-button slot="append" size="small" type="primary" @click="sendMessage">发送</el-button>
      </el-input> -->
    </div>
  </div>
</template>

<script>
  import UserAvatar from '@/components/UserAvatar';
  import { mapGetters } from 'vuex';
  import {getUserInfoChat, getMessages, readAllChat, readOneChat} from '@/api/message';

  export default {
    components: {
      UserAvatar
    },
    computed: {
      ...mapGetters([
        'identityid',
        'userdataid',
        'username',
        'avatar',
        'roles'
      ]),
    },
    data() {
      return {
        toUserId: this.$route.query.toUserId,
        toUserRole: this.$route.query.toUserRole,
        toUserName: '',
        toUserHeadImage: '',
        toUserMobile: '',
        message: '',
        messages: [],
        pageIndex: 1,
        loading: false,
        finished: true,
        showChatMore: false,
        messageSize: {
          maxHeight: 60,
          minHeight: 30
        },
      };
    },
    beforeCreate: function () {},
    created() {      
      console.log(this.userdataid);
      let that = this;
      this.$Ws.onmessage = function (e) {
        that.onMessage(e);
      };
      this.getToUserInfo();
      this.getMessages();
    },
    methods: {
      getToUserInfo() {
        getUserInfoChat({
          'user_data_id': this.toUserId,
          'user_role': this.toUserRole
        }).then(m => {
          console.log(m);
          if (m.code == 0) {
            let toUser = m.data;
            this.toUserName = toUser.name;
            this.toUserHeadImage = toUser.head_image;
            this.toUserMobile = toUser.mobile;
          } else {
            this.$message(m.data.msg);
          }
        });
      },
      getMessages() {
        this.loading = true;
        getMessages({
          'to_user_id': this.toUserId,
          'to_user_role': this.toUserRole,
          'page_index': this.pageIndex
        }).then(m => {
          if (m.code == 0) {
            let datas = m.data.list;
            datas.forEach(msg => {
              this.messages.unshift(msg);
            });
            this.loading = false;
            this.pageIndex = this.pageIndex + 1;
            let isNext = m.data.has_next_page;
            this.finished = !isNext;
            this.readAllMessage();
          } else {
            this.$message(m.data.msg);
            this.loading = false;
          }
        })
          .catch(error => {
            this.$message('获取消息失败，错误信息' + error);
            this.loading = false;
          });
      },
      readAllMessage() {
        readAllChat({
          'from_user_id': this.toUserId,
          'from_user_role': this.toUserRole,
        }).then();
      },
      readOneMessage(chatID) {
        readOneChat({
          'chat_id': chatID,
          'to_user_id': this.toUserId,
          'to_user_role': this.toUserRole,
        }).then();
      },
      onMessage(event) {
        let msg = JSON.parse(event.data);
        let textMsg;
        if (msg) {
          textMsg = msg.data;
        }
        if (textMsg && textMsg.content) {
          if (textMsg.to_user_id == this.userdataid && textMsg.to_user_role == this.roles) {
            var msgObj = {
              chat_id: textMsg.chat_id,
              content: textMsg.content,
              from_user_id: textMsg.from_user_id,
              send_time: textMsg.send_time,
              to_user_id: textMsg.to_user_id
            };
            this.messages.push(msgObj);
            console.log(msgObj);
            this.readOneMessage(textMsg.chat_id);

            this.$nextTick(() => {
              this.scrollEnd();
            });
          }
        }
      },
      sendMessage() {
        var msgObj = {
          chat_id: 0,
          content: this.message,
          from_user_id: this.userdataid,
          from_user_role: this.roles,
          send_time: new Date(),
          to_user_id: this.toUserId,
          to_user_role: this.toUserRole,
        };
        this.messages.push(msgObj);

        let strMsg = {
          'type': 2,
          'data': msgObj
        };
        let msg = JSON.stringify(strMsg);

        this.$Send(msg);
        this.message = '';
        
        this.$nextTick(() => {
          this.scrollEnd();
        });
      },
      buildChat(message) {
        var chat = '<li class="message">' + message + '</li>';
      },
      buildMyChat(message) {
        console.log(message);
      },
      formatTime(dateTime) {
        return this.$Shared.formatDateTime(dateTime);
      },
      scrollEnd(){
        let height = document.body.scrollHeight || document.documentElement.scrollHeight;
        window.scrollTo(0, height);
      },
      showImage(){}
    }
  };

</script>

<style scoped>

</style>
